﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jurassic.Library;
using Jurassic;
using Flower.Directory.Scripting;
using Flower.Directory.Util;
using Flower.Services.Data;
using System.Xml;

namespace Flower.Directory.Management.Scripting
{
    internal class JsonToSpringContainer : ClrFunction
    {
        private const string XMLNS = "http://www.springframework.net";

        public JsonToSpringContainer(ScriptEngine engine)
            : base
            (
                engine.Function.InstancePrototype,
                "__jsonToSpringContainer",
                engine.Object.InstancePrototype
            )
        {
        }

        [JSCallFunction]
        public XmlObject Exec(ObjectInstance json, int format)
        {
            Blob blob = 
                BlobUtil.WriteBlob
                (
                    (BlobFormat)format,
                    writer => 
                    {
                        writer.WriteStartDocument();
                        writer.WriteStartElement("objects", XMLNS);

                        foreach (PropertyNameAndValue prop in json.Properties)
                        {
                            var obj = prop.Value as ObjectInstance;

                            if (obj != null)
                            {
                                WriteObject(writer, prop.Name, obj);
                            }
                        }

                        writer.WriteEndElement();
                        writer.WriteEndDocument();
                    }
                );

            return new XmlObject(Engine.Object.InstancePrototype, blob);
        }

        private void WriteAttribute(XmlWriter writer, ObjectInstance json, string jsonName, string xmlName)
        {
            object attr = json[jsonName];

            if (attr != null && !(attr is Undefined))
            {
                writer.WriteAttributeString(xmlName, attr.ToString());
            }
        }

        private void WriteObject(XmlWriter writer, string id, ObjectInstance json)
        {
            writer.WriteStartElement("object", XMLNS);

            if (id != null)
            {
                writer.WriteAttributeString("id", id);
            }

            WriteAttribute(writer, json, "$type", "type");
            WriteAttribute(writer, json, "$factoryMethod", "factory-method");
            WriteAttribute(writer, json, "$factoryObject", "factory-object");
            WriteAttribute(writer, json, "$scope", "scope");

            foreach (PropertyNameAndValue prop in json.Properties)
            {
                if 
                (
                    prop.Name == "$type" ||
                    prop.Name == "$factoryMethod" ||
                    prop.Name == "$factoryObject" ||
                    prop.Name == "$scope"
                )
                {
                    continue;
                }

                if (prop.Name == "$constructor")
                {
                    var arrValue = prop.Value as ArrayInstance;
                    var objValue = prop.Value as ObjectInstance;

                    if (arrValue != null)
                    {
                        WriteConstructorArgs(writer, arrValue);
                    }
                    else if (objValue != null)
                    {
                        WriteConstructorArgs(writer, objValue);
                    }
                    else
                    {
                        throw new JavaScriptException(Engine, "Error", "Value of $constructor attribute must be either an array or an object.");
                    }
                }
                else
                {
                    writer.WriteStartElement("property", XMLNS);
                    writer.WriteAttributeString("name", prop.Name);

                    WriteValue(writer, prop.Value);

                    writer.WriteEndElement();
                }
            }

            writer.WriteEndElement();
        }

        private void WriteConstructorArgs(XmlWriter writer, ArrayInstance args)
        {
            foreach (object el in args.ElementValues)
            {
                writer.WriteStartElement("constructor-arg", XMLNS);

                WriteValue(writer, el);

                writer.WriteEndElement();
            }
        }

        private void WriteConstructorArgs(XmlWriter writer, ObjectInstance args)
        {
            foreach (PropertyNameAndValue prop in args.Properties)
            {
                writer.WriteStartElement("constructor-arg", XMLNS);
                writer.WriteAttributeString("name", prop.Name);

                WriteValue(writer, prop.Value);

                writer.WriteEndElement();
            }
        }

        private void WriteValue(XmlWriter writer, object value)
        {
            if (value is Null)
            {
                writer.WriteStartElement("null", XMLNS);
                writer.WriteEndElement();
                return;
            }

            var objValue = value as ObjectInstance;
            var arrValue = value as ArrayInstance;

            if (objValue != null && arrValue == null)
            {
                object refValue = objValue["$ref"];
                object type = objValue["$type"];

                if (refValue != null && !(refValue is Undefined))
                {
                    writer.WriteStartElement("ref", XMLNS);
                    writer.WriteAttributeString("object", refValue.ToString());
                    writer.WriteEndElement();
                }
                else
                {
                    if (type != null && !(type is Undefined))
                    {
                        WriteObject(writer, null, objValue);
                    }
                    else
                    {
                        writer.WriteStartElement("dictionary", XMLNS);

                        foreach (PropertyNameAndValue prop in objValue.Properties)
                        {
                            writer.WriteStartElement("entry", XMLNS);
                            writer.WriteAttributeString("key", prop.Name);

                            WriteValue(writer, prop.Value);

                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement();
                    }
                }
            }
            else
            {
                if (arrValue != null)
                {
                    writer.WriteStartElement("list", XMLNS);

                    foreach (object el in arrValue.ElementValues)
                    {
                        WriteValue(writer, el);
                    }

                    writer.WriteEndElement();
                }
                else
                {
                    writer.WriteStartElement("value", XMLNS);
                    writer.WriteCData((value is bool) ? value.ToString().ToLower() : value.ToString());
                    writer.WriteEndElement();
                }
            }
        }
    }
}
